﻿package framework.core;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Creation date: (2003-08-28)
 * @author: adminnistrator
 * servlet运行上下文类
 * 1 得到action_code
 * 2 从request中得到参数值(可做转化)
 * 3 设置转向页面,错误页面，错误提示信息
 * 4 放置request,session参数, 
 * 5 得到PageData
 */
public class SrvContext
{
	private static final int UPLOAD_MAX = 1024 * 1024 * 10; //上传文件最大 10M
	private FileUploadContentFactory m_upload_content = null; //上传文件时使用
	public HttpServletRequest m_req; //request
	public HttpServletResponse m_res; //response
	private boolean m_abs_path = false; //是否绝对路径
	private String m_next_url; //转向页面
	private String m_error_url; //error转向页面
	private String m_error_msg = null; //错误信息 
	private HashMap m_values = new HashMap(); //传递参数

	//constructer
	public SrvContext(HttpServletRequest req, HttpServletResponse res)
		throws Exception
	{
		m_upload_content =
			FileUploadContentFactory.getContentFactory(req, UPLOAD_MAX);
		m_req = req;
		m_res = res;
	}
	public ServletOutputStream getServletOutputStream() throws Exception
	{
		return m_res.getOutputStream();
	}

	//parameter interface
	public String getString(String name) throws Exception
	{
		String s = null;
		if (m_upload_content != null)
		{
			s = m_upload_content.getParameter(name);
		} else
		{
			s = m_req.getParameter(name);
			s = fixString(s);
		}
		return s;
	}
	public String getString(String name, String defValue) throws Exception
	{
		String value = getString(name);
		if (value == null)
			return defValue;
		return value;
	}
	public int getInt(String name) throws Exception
	{
		String s = getString(name);
		return Integer.parseInt(s);
	}
	public int getInt(String name, int defValue)
	{
		try
		{
			return getInt(name);
		} catch (Exception e)
		{
			return defValue;
		}
	}
	public int[] getInts(String name) throws Exception
	{
		String[] strArray = getParameterValues(name);
		if (strArray == null || strArray.length == 0)
		{
			return new int[0];
		}
		int[] intArray = new int[strArray.length];
		String str;
		for (int i = 0; i < strArray.length; i++)
		{
			str = strArray[i];
			intArray[i] = Integer.parseInt(str);
		}
		return intArray;
	}

	public double getDouble(String name) throws Exception
	{
		String s = getString(name);
		return Double.parseDouble(s);
	}
	public double getDouble(String name, double defValue)
	{
		try
		{
			return getDouble(name);
		} catch (Exception e)
		{
			return defValue;
		}
	}
	public boolean getBoolean(String name) throws Exception
	{
		String s = getString(name);
		if (null == s)
			return false;
		if (s.equalsIgnoreCase("true"))
		{
			return true;
		}
		return false;
	}
	public FileHolder getFile(String name)
	{
		if (m_upload_content != null)
		{
			return m_upload_content.getFileParameter(name);
		}
		return null;
	}
	public FileHolder[] getFiles(String name)
	{
		if (m_upload_content != null)
		{
			return m_upload_content.getFileParameterValues(name);
		}
		return null;
	}
	public Enumeration getParameterNames()
	{
		if (m_upload_content != null)
		{
			return m_upload_content.getParameterNames();
		} else
		{
			return m_req.getParameterNames();
		}
	}
	public Map getParameterMap()
	{
		return m_req.getParameterMap();
	}
	public String[] getParameterValues(String name) throws Exception
	{
		if (m_upload_content != null)
		{
			String[] strings = m_upload_content.getParameterValues(name);
			for (int i = 0; i < strings.length; i++)
			{
				strings[i] = fixString(strings[i]);
			}
			return strings;
		} else
		{
			String[] strings = m_req.getParameterValues(name);
			if (strings == null)
				return null;
			for (int i = 0; i < strings.length; i++)
			{
				strings[i] = fixString(strings[i]);
			}
			return strings;
		}
	}

	//data 
	public Object getValue(String name)
	{
		return m_values.get(name);
	}
	public void setValue(String name, Object v)
	{
		m_values.put(name, v);
	}

	//session interface
	public Object getSessionValue(String name)
	{
		HttpSession session = m_req.getSession();
		return session.getAttribute(name);
	}
	public void setSessionValue(String name, Object v)
	{
		//m_values.put(name,v);
		HttpSession session = m_req.getSession();
		session.setAttribute(name, v);
	}

	//control interface
	public String getActionCode() throws Exception
	{
		return getString("action_code");
	}
	public String getNextUrl()
	{
		return m_next_url;
	}
	public String getErrorUrl()
	{
		return m_error_url;
	}
	public String getErrorMsg()
	{
		return m_error_msg;
	}
	public void setNextUrl(String v)
	{
		m_next_url = v;
	}
	public void setErrorUrl(String v)
	{
		m_error_url = v;
	}
	public void setErrorMsg(String v)
	{
		m_error_msg = v;
	}

	public boolean isAbsPath()
	{
		return m_abs_path;
	}
	public void setAbsPath(boolean v)
	{
		m_abs_path = v;
	}

	//从request得到SrvContext
	public static SrvContext getContext(HttpServletRequest req)
		throws Exception
	{
		SrvContext context = (SrvContext) req.getAttribute("SrvContext");
		if (context != null)
			return context;
		return new SrvContext(req, null);
	}
	//放置SrvContext到request
	public static void setContext(HttpServletRequest req, SrvContext context)
	{
		req.setAttribute("SrvContext", context);
	}

	public static String fixString(String str) throws Exception
	{

		if (str == null)
			return null;
		//resin
		if (Config.getWebServerType().equalsIgnoreCase(Config.WEBSERVER_RESIN))
		{
			return new String(str.getBytes("8859_1"), "utf-8");
		}
		if (Config
			.getWebServerType()
			.equalsIgnoreCase(Config.WEBSERVER_TOMCAT))
		{
			return new String(str.getBytes("8859_1"), "utf-8");
		}

		//weblogic	
		if (Config
			.getWebServerType()
			.equalsIgnoreCase(Config.WEBSERVER_WEBLOGIC))
		{
			String localStr = Locale.getDefault() + "";
			//zh_CN
			if (localStr.equals("zh_CN"))
				return new String(str.getBytes("8859_1"), "utf-8");

			//en_US
			if (localStr.equals("en_US"))
			{
				return new String(str.getBytes("8859_1"), "utf-8");
			}
			Logger.throwException(
				"SrvContext.getString()",
				"unknown Locale,webServer=weblogic,local=" + localStr);
		}
		Logger.throwException(
			"SrvContext.getString()",
			"unknown web-server! webServer=" + Config.getWebServerType());
		return null;
	}

	public String getParametersStr() throws Exception
	{
		String result = "";
		Enumeration params = getParameterNames();
		while (params.hasMoreElements())
		{
			String param = (String) params.nextElement();
			result += param;
			result += "=";
			result += (String) getValue(param);
			result += ";\n";
		}
		return result;
	}
	
	
	//保存Cookies
	public void setCookie(String cookieName,String cookieValue) throws Exception
	{
		Cookie cookie = new Cookie(cookieName,cookieValue); 
		cookie.setMaxAge(365*24*60*60); 
		m_res.addCookie(cookie); 
	}
		
	//读取Cookies
	public String getCookie(String cookieName) throws Exception
	{
		String value = "";
		Cookie[] cookies = m_req.getCookies();//取客户端所有cookie
		if(cookies != null)
		{
			for (int i=0;i<cookies.length;i++)
			{
				Cookie c = cookies[i];
				if (c.getName().equalsIgnoreCase(cookieName))
				{
					value = c.getValue();
					break;
				}
			}
		}		
		return value;
	}
	
	public static String ParamSessionName = "ParamMap";
	public String outputContent() throws Exception
	{
		String output = "";
		//HashMap map = (HashMap)getSessionValue(ParamSessionName);
		Map map = (Map)getSessionValue(ParamSessionName);
		if(map == null) 
			return output;
		Set paramNames = map.keySet();
		Iterator iter = paramNames.iterator();
		while(iter.hasNext())
		{ 
			Object paramName = iter.next();
			Object temp = map.get(paramName);
			String[] paramValueArrays = (String[])temp;
			//System.out.println(((String[])paramValueArrays)[0]);
			for(int i=0; i<paramValueArrays.length; i++)
				output += "<input type='hidden' name='"+ fixString((String)paramName) +"' value='"+ fixString(paramValueArrays[i])+"'>\n";
		}
		
		return output;
	}
	
	
	public String getRemoteAddr() throws Exception
	{
		return m_req.getRemoteAddr();
	}
	
	
	
}
